package com.mspbots.rule.exceptions.attendance;

import com.mspbots.cw.request.AttendanceDTO;
import com.mspbots.cw.request.TenantUserConfigurationDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @ClassName com.mspbots.rule.exceptions.attendance.LongBreak
 * @Description TODO
 * @Author Jun
 * @Date 2019/10/11 14:06
 * @Version 1.0
 **/
@Slf4j
@Rule(name = "BreakTooLong",
        description = "Dear [user], it is [current time][Timezone label], " +
                "you are scheduled to start working at [scheduled starting time]. " +
                "Please log in with [Software_of_time_keeping] when you started to work.")
public class BreakTooLong extends AttendanceBaseRule {

    @Condition
    public boolean condition(@Fact(FACT) TenantUserConfigurationDTO tenantUserConfigurationDTO) {
        try {
            if (!setUserMapping(tenantUserConfigurationDTO.getTenantUserId())
                    || super.checkDayMessage(tenantUserConfigurationDTO.getTenantUserId())
                    || ObjectUtils.isEmpty(this.tenantRuleDTO.getRuleParams())) {
                return false;
            }

            // get last attendance
            AttendanceDTO attendanceDTO = getAttendance(Map.of("tenantId", tenantUserConfigurationDTO.getTenantId(),
                    "userId", tenantUserConfigurationDTO.getTenantUserId()));
            if (ObjectUtils.isEmpty(attendanceDTO) || !"BREAK".equalsIgnoreCase(attendanceDTO.getType()) || !in12Hour(attendanceDTO)) {
                return false;
            }
            Integer mins = this.tenantRuleDTO.getRuleParams().get("Mins").asInt();

            //if logTime < now - mins
            if (logTimeUTC(attendanceDTO).isBefore(LocalDateTime.now().minusMinutes(mins))) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("BreakTooLong error : [{}] ", tenantUserConfigurationDTO.getTenantUserId());
        }
        return false;
    }


}
